package org.dyk.seamanshousefrontdesk.service.orders;

import org.dyk.seamanshousefrontdesk.model.Cart;
import org.dyk.seamanshousefrontdesk.model.Orders;
import org.dyk.seamanshousefrontdesk.repository.CartRepository;
import org.dyk.seamanshousefrontdesk.repository.OrdersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.Date;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService{
    @Autowired
    private OrdersRepository ordersRepository;
    @Autowired
    private CartRepository cartRepository;

    /**
     * 根据 主键 获取订单信息
     * @param oid
     * @return
     */
    @Override
    public Orders findByOid(int oid) {
        return ordersRepository.findByOid(oid);
    }

    /**
     * 获取当前的登录用户的订单信息
     * @param uid
     * @return
     */
    @Override
    public List<Orders> findAllByUid(int uid) {
        return ordersRepository.findAllByUid(uid);
    }

    /**
     * 确认收货操作
     * @param oid
     * @return
     */
    @Override
    public boolean updata(int oid) {
        Orders byOid = ordersRepository.findByOid(oid);
        byOid.setOrdersState(3);
        ordersRepository.save(byOid);
        return true;
    }

    /**
     * 支付完成操作
     * @param out_trade_no
     * @return
     */
    @Override
    public boolean payOut(int out_trade_no) {
        Orders byOid = ordersRepository.findByOid(out_trade_no);
        byOid.setOrdersState(1);
        ordersRepository.save(byOid);
        return true;
    }

    /**
     * 添加订单
     * @param cid
     * @param uid
     * @param quantity
     * @param price
     * @param consignee
     * @param phone
     * @param address
     * @return
     */
    @Override
    public boolean insert(int cid, int uid, int quantity, int price,
                          String consignee,
                          String phone,
                          String address) {
        Cart cart = cartRepository.findByCid(cid);
        //生成订单
        Orders orders = new Orders();
        orders.setGid(cart.getGid());
        orders.setUid(uid);
        orders.setOrdersQuantity(quantity);
        orders.setOrdersPrice(price);
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        orders.setOrdersDate(date);
        orders.setOrdersState(0);
        orders.setConsignee(consignee);
        orders.setPhone(phone);
        orders.setAddress(address);
        ordersRepository.save(orders);
        //删除购物车信息
        cartRepository.delete(cart);
        return true;
    }
}
